package com.ts.api.http.receive.biz;

import com.gitee.apanlh.util.algorithm.encrypt.symmetric.AES;
import com.gitee.apanlh.util.base.ChooseEq;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.reflection.CopyUtils;
import com.gitee.apanlh.util.valid.Assert;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.common.constant.api.ApiEnum;
import com.ts.api.common.context.ApiContext;
import com.ts.api.common.entity.ApiParameter;
import com.ts.api.common.util.ApiDictUtils;
import com.ts.api.exp.ApiMsgException;
import com.ts.api.http.receive.entity.apply.req.ApiReceiveApplyChengXinHua;
import com.ts.api.http.receive.entity.dataexchange.req.ApiReceiveDataExchangeChengXinHua;
import com.ts.api.module.api.convert.core.annotation.ApiReceive;
import com.ts.api.module.api.convert.core.annotation.ApiReceiveConvertType;
import com.ts.api.module.api.convert.receive.entity.ApiReceiveApply;
import com.ts.api.module.api.convert.receive.entity.ApiReceiveDecrypt;
import com.ts.api.module.api.convert.receive.entity.ApiReceiveNotice;
import com.ts.api.module.api.convert.receive.entity.ApiReceivePhoneMd5DataExchange;
import com.ts.api.module.api.convert.receive.handler.ApiReceivePhoneMd5ConvertHandler;
import com.ts.api.module.api.entity.ApiUserRequest;

import java.util.Map;

/**
 * 橙薪花-V3安心分期 上游
 * https://docs.qq.com/doc/DR3V2Zk5DeklDWG1X
 *
 * @author 李源聪
 */
@ApiReceive(apiClientId = "1941130693455007744",type = ApiReceiveConvertType.API_CHANNEL_PHONE_MD5)
public class ApiReceivePhoneMd5ChengXinHua implements ApiReceivePhoneMd5ConvertHandler {

    private static final String KEY = "kM3pR9tX2sB6vQ8w";

    @Override
    public Map<String, String> requireParam(RequestVO requestVO) throws Exception {
        Map<String, Object> map = JsonUtils.toMap(requestVO.getBody());

        //  传递什么，验证什么Key
        String source = String.valueOf(map.get("source"));
        String data = String.valueOf(map.get("data"));
        String timestamp = String.valueOf(map.get("timestamp"));
        String pid = String.valueOf(map.get("pid"));
        String ordernum = String.valueOf(map.get("ordernum"));

        Assert.isNotEmptyThrows(source, new ApiMsgException(ApiEnum.API_RECEIVE_BODY_MISS.format("source")));
        Assert.isNotEmptyThrows(data, new ApiMsgException(ApiEnum.API_RECEIVE_BODY_MISS.format("data")));
        Assert.isNotEmptyThrows(timestamp, new ApiMsgException(ApiEnum.API_RECEIVE_BODY_MISS.format("timestamp")));
        Assert.isNotEmptyThrows(pid, new ApiMsgException(ApiEnum.API_RECEIVE_BODY_MISS.format("pid")));
        Assert.isNotEmptyThrows(ordernum, new ApiMsgException(ApiEnum.API_RECEIVE_BODY_MISS.format("ordernum")));
        ApiParameter apiParameter = ApiContext.PARAMETER.get();
        apiParameter.put("pid", pid);
        apiParameter.put("ordernum", ordernum);

        //  返回需要的数据Map
        return MapUtils.newHashMap(newMap -> {
            newMap.put("source", source);
            newMap.put("data", data);
            newMap.put("timestamp", timestamp);
            newMap.put("pid", pid);
            newMap.put("ordernum", ordernum);
        });
    }

    @Override
    public ApiReceiveDecrypt decrypt(Map<String, String> paramMap, RequestVO requestVO) throws Exception {
        String data = paramMap.get("data");
        AES ecb = AES.createEcb(KEY.getBytes());
        String string = ecb.decryptFromBase64Str(data);

        return new ApiReceiveDecrypt(string);
    }

    @Override
    public ApiUserRequest parseDataExchange(ApiReceiveDecrypt apiReceiveDecrypt) throws Exception {
        ApiReceiveDataExchangeChengXinHua parse = apiReceiveDecrypt.parse(ApiReceiveDataExchangeChengXinHua.class);
        ApiUserRequest apiUserRequest = CopyUtils.copy(parse, ApiUserRequest.class);
        fieldMapping(apiUserRequest);
        return apiUserRequest;
    }

    @Override
    public Map<String, Object> respDataExchange(ApiReceivePhoneMd5DataExchange dataExchangeMessage) throws Exception {
        boolean suc = dataExchangeMessage.hasBizSuc();
        ApiParameter apiParameter = ApiContext.PARAMETER.get();
        // 失败
        if (!suc) {
            Map<String, Object> resultMap = MapUtils.newLinkedHashMap();
            resultMap.put("code", "300");
            resultMap.put("message", "撞库失败-"+dataExchangeMessage.getBizMsg());
            resultMap.put("data", MapUtils.newLinkedHashMap(dataMap -> {
                dataMap.put("pid", apiParameter.get("pid"));
                dataMap.put("ordernum", apiParameter.get("ordernum"));
            }));
            return resultMap;
        }

        //成功
        Map<String, Object> resultMap = MapUtils.newLinkedHashMap();
        resultMap.put("code", "200");
        resultMap.put("message", "可进件");
        resultMap.put("data", MapUtils.newLinkedHashMap(dataMap -> {
            //  产品原本价格（CPS分润模式必须返回价格）CPA模式无价格返回
            dataMap.put("Price", dataExchangeMessage.getPrice());
            //  机构名称
            dataMap.put("Company", dataExchangeMessage.getOrgName());
            //  产品logo
            dataMap.put("logo", dataExchangeMessage.getLogoPath());
            //  产品名称
            dataMap.put("ProductName", dataExchangeMessage.getDisplayName());
            //  地址
            dataMap.put("Address", "");
            // 订单编号
            dataMap.put("ordernum", apiParameter.get("ordernum"));
            dataMap.put("pid", apiParameter.get("pid"));
        }));
        return resultMap;
    }

    @Override
    public ApiUserRequest parseApply(ApiReceiveDecrypt apiReceiveDecrypt) throws Exception {
        ApiReceiveApplyChengXinHua parse = apiReceiveDecrypt.parse(ApiReceiveApplyChengXinHua.class);
        ApiUserRequest apiUserRequest = CopyUtils.copy(parse, ApiUserRequest.class);
        fieldMapping(apiUserRequest);
        return apiUserRequest;
    }

    @Override
    public Map<String, Object> respApply(ApiReceiveApply applyMessage) throws Exception {
        boolean suc = applyMessage.hasBizSuc();
        // 失败
        if (!suc) {
            Map<String, Object> resultMap = MapUtils.newLinkedHashMap();
            resultMap.put("code", "300");
            resultMap.put("message", "进件失败-"+applyMessage.getBizMsg());
            return resultMap;
        }

        // 成功
        Map<String, Object> resultMap = MapUtils.newLinkedHashMap();
        resultMap.put("code", "200");
        resultMap.put("message", "进件成功");
        return resultMap;
    }

    @Override
    public void fieldMapping(ApiUserRequest apiUserRequest) {

        // sex 性别（1男 2女）
        // sex 性别
        // 0 男
        // 1 女
        // 2 未知
        String sex = apiUserRequest.getSex();
        if (ValidParam.isNotEmpty(sex)) {
            String value = ChooseEq.create()
                    .when(sex, "1", "0")
                    .when(sex, "2", "1")
                    .end("2");
            apiUserRequest.setSex(value);
        }
        // age 年龄
        String age = ApiDictUtils.convertAge(apiUserRequest.getAge());
        apiUserRequest.setAge(age);

        // 贷款额度 20万以上=1 10万-20万=2 5万-10万=3 1万-5万=4 1万以内=5
        // loanAmount 贷款金额
        // 1 3万以下
        // 2 5万-10万
        // 3 10万-20万
        // 4 20万以上
        if (ValidParam.isNotEmpty(apiUserRequest.getLoanAmount())) {
            String value = ChooseEq.create()
                    .when(apiUserRequest.getLoanAmount(), "1", "4")
                    .when(apiUserRequest.getLoanAmount(), "2", "3")
                    .when(apiUserRequest.getLoanAmount(), "3", "2")
                    .when(apiUserRequest.getLoanAmount(), "4", "1")
                    .when(apiUserRequest.getLoanAmount(), "5", "1")
                    .end();
            apiUserRequest.setLoanAmount(value);
        }

        // 芝麻分 700分以上=1 650-699分=2 600-649分=3 600分以下=4
        // sesameCredit 芝麻分
        // 1 600分以下
        // 2 600~649分
        // 3 650~699分
        // 4 700分以上
        if (ValidParam.isNotEmpty(apiUserRequest.getSesameCredit())) {
            String value = ChooseEq.create()
                    .when(apiUserRequest.getSesameCredit(), "1", "4")
                    .when(apiUserRequest.getSesameCredit(), "2", "3")
                    .when(apiUserRequest.getSesameCredit(), "3", "2")
                    .when(apiUserRequest.getSesameCredit(), "4", "1")
                    .end();
            apiUserRequest.setSesameCredit(value);
        }
        // 花呗额度 5000元以上=1 5000元以内=2 无花呗额度=3
        // 蚂蚁花呗可用额度
        // 2 3千以下
        // 3 3千-1万
        // 4 1万-3万
        // 5 3万以上
        // 1 无额度
        if (ValidParam.isNotEmpty(apiUserRequest.getHbLimit())) {
            String value = ChooseEq.create()
                    .when(apiUserRequest.getHbLimit(), "1", "3")
                    .when(apiUserRequest.getHbLimit(), "2", "2")
                    .when(apiUserRequest.getHbLimit(), "3", "1")
                    .end();
            apiUserRequest.setHbLimit(value);
        }
        // 白条额度 5000元以=1 5000元以内=2 无白条额度=3
        // 白条可用额度
        // 2 3千以下
        // 3 3千-1万
        // 4 1万-3万
        // 5 3万以上
        // 1 无额度
        if (ValidParam.isNotEmpty(apiUserRequest.getBtLimit())) {
            String value = ChooseEq.create()
                    .when(apiUserRequest.getBtLimit(), "1", "3")
                    .when(apiUserRequest.getBtLimit(), "2", "2")
                    .when(apiUserRequest.getBtLimit(), "3", "1")
                    .end();
            apiUserRequest.setBtLimit(value);
        }
        //信用状况 当前无逾期=1 当前有逾期=2
        // 信用情况（逾期）
        // 1.无逾期
        // 2.当前有逾期
        // 3.一年以内无逾期
        if (ValidParam.isNotEmpty(apiUserRequest.getOverdue())) {
            String value = ChooseEq.create()
                    .when(apiUserRequest.getOverdue(), "1", "1")
                    .when(apiUserRequest.getOverdue(), "2", "2")
                    .end();
            apiUserRequest.setOverdue(value);
        }
        // 房产 有房产=1 无房产=0
        // 房产情况
        // 1-无房产
        // 2-有房不抵押
        // 3-有房可抵押
        // 4-有房产
        // 5-有按揭房产
        // 6-有全款房产
        if (ValidParam.isNotEmpty(apiUserRequest.getRealEstateInfo())) {
            String value = ChooseEq.create()
                    .when(apiUserRequest.getRealEstateInfo(), "0", "1")
                    .when(apiUserRequest.getRealEstateInfo(), "1", "4")
                    .end();
            apiUserRequest.setRealEstateInfo(value);
        }
        // 车产 有车=1 无车产=0
        // 车辆情况
        // 1.无车产
        // 2.有车不抵押
        // 3.有车可抵押
        // 4.有车
        if (ValidParam.isNotEmpty(apiUserRequest.getCarInfo())) {
            String value = ChooseEq.create()
                    .when(apiUserRequest.getCarInfo(), "0", "1")
                    .when(apiUserRequest.getCarInfo(), "1", "4")
                    .end();
            apiUserRequest.setCarInfo(value);
        }
        // 公积金 有公积金=1 无公积金=0
        // 公积金
        // 1.无公积金
        // 2.缴纳6个月以下
        // 3.缴纳6个月以上
        // 4.有公积金
        if (ValidParam.isNotEmpty(apiUserRequest.getProvidentFund())) {
            String value = ChooseEq.create()
                    .when(apiUserRequest.getProvidentFund(), "0", "1")
                    .when(apiUserRequest.getProvidentFund(), "1", "4")
                    .end();
            apiUserRequest.setProvidentFund(value);
        }
        // 营业执照 有营业执照=1 无营业执照=0
        // 营业执照注册年限
        // 1 未注册
        // 2 注册1年以下
        // 3 注册1~5年
        // 4 注册5年以上
        if (ValidParam.isNotEmpty(apiUserRequest.getBizLicenseYear())) {
            String value = ChooseEq.create()
                    .when(apiUserRequest.getBizLicenseYear(), "0", "1")
                    .when(apiUserRequest.getBizLicenseYear(), "1", "2")
                    .end();
            apiUserRequest.setBizLicenseYear(value);
        }

        // 社保 有社保=1 无社保=0
        // 社保缴纳
        // 1-无社保
        // 2-缴纳6个月以下
        // 3-缴纳6个月以上
        // 4-有社保
        if (ValidParam.isNotEmpty(apiUserRequest.getSocialSecurity())) {
            String value = ChooseEq.create()
                    .when(apiUserRequest.getSocialSecurity(), "0", "1")
                    .when(apiUserRequest.getSocialSecurity(), "1", "4")
                    .end();
            apiUserRequest.setSocialSecurity(value);
        }
    }

    @Override
    public Object reqPullApplyNotice(ApiReceiveNotice apiReceiveNotice) {
        return null;
    }

    @Override
    public boolean respPullApplyNotice(String responseBody) {
        return false;
    }

    @Override
    public Object reqPushApplyNotice(ApiReceiveNotice apiReceiveNotice) {
        return null;
    }

    @Override
    public boolean respPushApplyNotice(String responseBody) {
        return false;
    }
}
